<template>
  <div class="main">
    <PageTitle/>
    <div class="mainContent">
      <div class="searchForm_cont searchForm_cont_bor">
        <SearchForm :search-form="searchForm" @search="search" />
      </div>
      <div class="table-bg">
        <div class="btn-box">
          <el-button type="primary" icon="el-icon-plus" @click="add">添加</el-button>
        </div>
        <vxe-table :table-data-column="tableDataColumn" :loading="loading"  :table-data="tableData"  :searjuery="searJuery" @handleCurrentChange="handleCurrentChange"
                   @handleSizeChange="handleSizeChange" @filterMethod="filterMethod">
          <template v-slot:btnGroups="{row}">
            <el-tooltip class="item" effect="dark" content="删除" placement="top">
              <vxe-button type="text" status="danger" icon="vxe-icon-delete"  @click="handleDelete(row)"></vxe-button></el-tooltip>
            <el-tooltip class="item" effect="dark" content="编辑" placement="top">
              <vxe-button type="text" status="primary" icon="vxe-icon-edit" @click="handleEdit(row)"></vxe-button></el-tooltip>
          </template>
        </vxe-table>
      </div>
    </div>
    <el-drawer
            :title="title"
            :visible.sync="drawer"
            direction="rtl"
            size="50%"
            :wrapperClosable="false"
            :before-close="handleClose">
      <div class="drawer-main">
        <div class="btn-drawer">
          <el-button type="primary" @click="handleSubmit" :loading="btnLoad" >保存</el-button>
          <el-button type="danger" plain @click="handleClose">取消</el-button>

        </div>
        <QuillEditorForm
                ref="enterpriseForm"
                :form-disabled="formDisabled"
                :form-data="formData"
                :form-ele="state === 'insert'?formEle:formEle1"
                :form-rules="formRules"
                label-width="220px"
                @selectLink="selectLink"/>
      </div>
    </el-drawer>
  </div>
</template>

<script>
  import SearchForm from "@/components/SearchForm/index";
  import VxeTable from "@/components/vxeTable";
  import PageTitle from "@/components/PageTitle/index";
  import {bcSubmitAlert} from '@/utils/bc-form-data';
  import QuillEditorForm from '@/components/QuillEditorForm'
  import {getUserList,addUser,deleteUser,getUserById,respassword,updateUser} from '@/api/user'
  import { getRoleForSearch,getDepartmentForSearch,getAreaTree } from '@/api/public'
  import {cooplistForSearch} from '@/api/basicInformation/cooperation'
  import ruleValidate from '@/utils/bc-validate'
  import {validateHanset } from '@/utils/validator'
  export default {
    name: "userIndex",
    components: {
      VxeTable,
      PageTitle,
      SearchForm,
      QuillEditorForm
    },
    data() {
      var passwordRepeat = (rule, value, callback) => {
        if (value.length == 0 || value == '') {
          callback(new Error('请确认密码'))
        } else if (value != this.form.data.userPwd) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }
      return {
        drawer:false,
        cascaderIndex1: 0,
        cascaderIndex2: 1,
        formDisabled: false,
        formData:{},
        formRules:{
          type: { required: true, message: '请选择所属应用', trigger: 'change' },
          userName: { required: true, message: '请输入账号', trigger: 'blur' },
          userRealName: { required: true, message: '请输入姓名', trigger: 'blur' },
          password:[{ required: true, message: '请输入密码长度8-20位，需同时包含数字、字母、特殊符合', trigger: 'blur' },
            {required: true, validator: ruleValidate.ruleValidator.validatePassWord, trigger: 'blur'}],
          userPhone:[{required: true, message: '请输入电话', trigger: 'blur'},
            {required: true, validator: validateHanset, trigger: 'blur'}],
          roleIds1:{ required: true, message: '请选择角色', trigger: 'change' },
          userStatus:{ required: true, message: '请选择状态', trigger: 'change' },
        },

        btnLoad:false,
        formEle: [
          {
            label: "所属应用",
            isshow: true,
            type: "select",
            key: "type",
            options:[{label:'备品库端',value:'3'},{label:'小程序端',value:'4'}],
            span: 24,
            required: true
          },
          {
            label: "账号",
            isshow: true,
            type: "input",
            key: "userName",
            required: true,
            span: 24,
          },
          {
            label: "姓名",
            isshow: true,
            type: "input",
            key: "userRealName",
            required: true,
            span: 24,
          },
          {
            label: "密码",
            isshow: true,
            type: "password",
            key: "password",
            required: true,
            span: 24,
          },
          {
            label: "电话",
            isshow: true,
            type: "input",
            key: "userPhone",
            required: true,
            span: 24,
          },
          {
            label: "邮箱",
            isshow: true,
            type: "input",
            key: "userEmail",
            required: false,
            span: 24,
          },
          {
            label: "身份证",
            isshow: true,
            type: "input",
            key: "idcard",
            required: false,
            span: 24,
          },
          {
            label: "角色",
            isshow: true,
            type: "multipleselect",
            key: "roleIds1",
            options:[],
            span: 24,
            required: true,
            filterable:true
          },{
            label: "所属备品库",
            isshow: true,
            type: "text-tip",
            key: "relevanceName",
            options:this.bpkList,
            span: 24,
            required: true,
          },
          {
            label: "状态",
            isshow: true,
            type: "select",
            key: "userStatus",
            options:[{label:'启用',value:'1'},{label:'停用',value:'0'}],
            span: 24,
            required: true
          },
        ],
        formEle1: [
          {
            label: "所属应用",
            isshow: true,
            type: "select",
            key: "type",
            options:[{label:'备品库端',value:'3'},{label:'小程序端',value:'4'}],
            span: 24,
            required: true
          },
          {
            label: "账号",
            isshow: true,
            type: "input",
            key: "userName",
            required: true,
            span: 24,
          },
          {
            label: "姓名",
            isshow: true,
            type: "input",
            key: "userRealName",
            required: true,
            span: 24,
          },
          {
            label: "密码",
            isshow: true,
            type: "password",
            key: "password",
            required: true,
            span: 24,
          },
          {
            label: "电话",
            isshow: true,
            type: "input",
            key: "userPhone",
            required: true,
            span: 24,
          },
          {
            label: "邮箱",
            isshow: true,
            type: "input",
            key: "userEmail",
            required: false,
            span: 24,
          },
          {
            label: "身份证",
            isshow: true,
            type: "input",
            key: "idcard",
            required: false,
            span: 24,
          },
          {
            label: "角色",
            isshow: true,
            type: "text-tip",
            key: "roleName",
            options:[],
            span: 24,
            required: true,
          },{
            label: "所属备品库",
            isshow: true,
            type: "text-tip",
            key: "relevanceName",
            options:this.bpkList,
            span: 24,
            required: true,
          },
          {
            label: "状态",
            isshow: true,
            type: "select",
            key: "userStatus",
            options:[{label:'启用',value:'1'},{label:'停用',value:'0'}],
            span: 24,
            required: true
          },
        ],
        searchForm: [
          {
            title: "账号",
            type: "input",
            value: "userName",
          },
          {
            title: "姓名",
            type: "input",
            value: "userRealName",
          },
          {
            title: "注册时间",
            type: "dateRange",
            value: "dateList",
          },
          {
            title: "状态",
            type: "select",
            value: "userStatus",
            options: [{label:'启用',value:1},{label:'停用',value:0}]
          },
        ],
        loading: false,
        tableData: [],
        tableDataColumn: [
          {
            label: "账号",
            key: "userName",
            sortable: false,
          },
          {
            label: "姓名",
            key: "userRealName",
            sortable: false,
          },
          {
            label: "角色",
            key: "roleNameGroup",
            sortable: true,
            filter:true
          },

          {
            label: "邮箱",
            key: "userEmail",
            sortable: false,
          },
          {
            label: "电话",
            key: "userPhone",
            sortable: true,
            filter:true
          },
          {
            label: "创建时间",
            key: "userCreateTime",
            sortable: false,
          },
          {
            label: "状态",
            key: "userStatusName",
            sortable: false,
            type:'colors',

          },

        ],
        searJuery: {
          pageIndex: 1,
          pageSize: 10,
          total: 0
        },
        state:'insert',
        title:'新增用户',
        roleList: [],//所属角色下拉
        depList:[],//所属部门
        areaList:[]
      };
    },
    created() {
      this.getList();
    },
    watch:{

    },
    methods: {
      //获取角色下拉列表
      getRoleList(type) {
        getRoleForSearch({type:type}).then(res => {
          let arr = []
          let roleList = []
          if (type === '4'){
            res.data.map((item) => {
              if (item.roleName === '备品库故障件接收'){
                arr.push({label: item.roleName, value: item.roleId})
              }
            })
          }else{
            res.data.map((item) => {
              if (item.roleName === '备品库管理员'){
                arr.push({label: item.roleName, value: item.roleId})
              }
            })
          }
          this.roleList = roleList
          this.formEle[7].options = arr
        })
      },
      // 表单提交
      handleSubmit() {
        if(this.state =='edit'){
          delete this.formRules.password
        }
        this.$refs.enterpriseForm.getData().then(valid => {
          if (valid) {
            this.btnLoad=true
            this.$set(this.formData,'roleIds',JSON.stringify(this.formData.roleIds1))
            this.$set(this.formData,'relevanceName',this.$store.getters.userInfo.relevanceName)
            this.$set(this.formData,'relevanceId',this.$store.getters.userInfo.relevanceId)
            let data= Object.assign({},this.formData)
            delete data['roleIds1']
            const loading = this.$loading({
              lock: true,
              text: '处理中',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
            // 新增 修改
            if(this.state == 'insert'){
              this.btnLoad=false
              addUser(data).then( res =>{
                loading.close();
                this.btnLoad=false
                if(res.code ==1){
                  this.getList()
                  this.handleClose()
                }else{

                  this.$message.error(res.msg)
                }
              }).catch(err => {
                this.btnLoad = false
                loading.close();
              })
            }else {
              updateUser(data).then(res =>{
                this.btnLoad=false
                loading.close();
                if(res.code ==1){
                  this.getList()
                  this.handleClose()
                }else{
                  this.$message.error(res.msg)
                }
              }).catch(err => {
                this.btnLoad = false
                loading.close();
              })
            }
          }
        });
      },
      //所属应用选择后显示
      selectLink(e){
        if(e.key =='type'){
          let data = e.val
          this.$set(this.formData,'roleIds1',"")
          this.getRoleList(data)
        }
      },
      handleSizeChange(val) {
        this.searJuery.pageSize = val
        this.getList()
      },
      //列表分页
      handleCurrentChange(val) {
        this.searJuery.pageIndex = val
        this.getList()
      },
      //筛选功能
      filterMethod(data){
        this.$set(this.searJuery,data.field,data.datas)
        this.getList()
      },
      //获取用户列表
      getList() {
        delete this.searJuery['page']
        delete this.searJuery['total']
        console.log(this.$store.getters.userInfo.relevanceId)
        this.$set(this.searJuery,'relevanceId',this.$store.getters.userInfo.relevanceId)
        getUserList(this.searJuery).then(res => {
          this.loading = false
          res.data.data.forEach( e=>{
            if(e.userStatus ==1){
              this.$set(e,'userStatusName','启用')
            }else{
              this.$set(e,'userStatusName','停用')
            }

          })
          this.tableData = res.data.data
          this.searJuery.total = Number(res.data.total)
        }).catch(() => {
          this.loading = false
          this.$message.error('数据异常，请联系管理员')
        })
      },

      //查询
      search(val) {
        this.loading = true
        if (JSON.stringify(val) == '{}') {
          this.searJuery = {
            pageIndex: 1,
            pageSize: 10,
            total: 0,
          }
        } else {
          for (const i in val) {
            this.searJuery[i] = val[i]
          }
          if(this.searJuery.dateList && this.searJuery.dateList.length >0 ){
            this.searJuery.trStartTimeStart=this.searJuery.dateList[0]
            this.searJuery.trStartTimeEnd=this.searJuery.dateList[1]
            delete this.searJuery['dateList']
          }
          this.searJuery.pageIndex = 1
        }
        this.getList()
      },


      //添加用户
      add() {
        this.drawer = true
        this.title = '新增用户'
        this.state='insert'
        this.formEle[3].disabled = false
        this.formEle[0].disabled = false
        this.formEle[1].disabled = false
        this.formEle[7].disabled = false
        Object.keys(this.formData).forEach(k => this.formData[k] = null)//清空之前填写数据
        this.$set(this.formData,'relevanceName',this.$store.getters.userInfo.relevanceName)
        this.$set(this.formData,'relevanceId',this.$store.getters.userInfo.relevanceId)
        //this.$refs.enterpriseForm.resetfields().then(res=>{})

      },

      //编辑用户
      handleEdit(row) {
        this.title = '编辑用户'
        this.formDisabled = false
        this.state='edit'
        this.formEle1[0].disabled = true
        this.formEle1[1].disabled = true
        this.formEle1[3].disabled = true
        this.formEle1[7].disabled = true
        this.getDetails(row)
      },




      //用户详情
      handleDetails(row) {
        this.title = '用户详情'
        this.formDisabled = true
        this.getDetails(row)
      },

      //获取用户详情
      getDetails(row) {
        bcSubmitAlert(getUserById, {id: row.userId}, true).then(res => {
          let roleIds=[]
          res.data.roleList.forEach(e=>{
            roleIds.push(e.roleId)
          })
          this.formData = res.data
          this.$set(this.formData,'roleName',row.roleNameGroup)
          this.$set(this.formData,'relevanceName',this.$store.getters.userInfo.relevanceName)
          this.$set(this.formData,'relevanceId',this.$store.getters.userInfo.relevanceId)
          this.$set(this.formData,'roleIds1',roleIds)
          delete this.formData['roleList']
          console.log('this.formData',this.formData)
          this.getRoleList(this.formData.type)
          // this.selectLink({'key':'type','val':this.formData.type})
          // this.selectLink({'key':'roleIds','val':this.formData.roleIds})
          this.drawer = true
        })
      },

      //删除
      handleDelete(row) {
        this.$confirm('确认删除当前用户', '删除用户', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteUser({id: row.userId}).then((res) => {
            if (res.code==1) {
              this.$message.success('操作成功');
              this.getList()
            } else {
              this.$message.error('操作失败');
            }
          });
        }).catch(() => {

        });
      },
      //重置密码
      respassword(row) {
        this.$confirm('确认重置当前用户密码', '重置密码', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          respassword({userId: row.userId}).then((res) => {
            if (res.code==1) {
              this.$message.success('操作成功');
              this.getList()
            } else {
              this.$message.error('操作失败');
            }
          });
        }).catch(() => {

        });
      },
      //关闭新增用户弹出框
      handleClose() {
        this.drawer = false
        this.btnLoad = false
        Object.keys(this.formData).forEach(k => this.formData[k] = null)//清空之前填写数据
        this.$refs.enterpriseForm.clearvalidate()
        this.$refs.enterpriseForm.resetfields();

      },


    },
  };
</script>
<style lang="scss" scoped>
  @import "~@/assets/css/style.css";
  .searchForm_cont_bor {
    overflow-y: hidden
  }
  .btn-box{
    margin-bottom: 20px;
    display: flex;
    justify-content: flex-end;
    padding-right: 40px;
  }
  .btn-drawer{
    margin-bottom: 20px;
    display: flex;
    justify-content: flex-end;
    .el-button{
      margin-right: 30px;
      &:last-child{
        margin-right:0px;
      }
    }
  }
  .drawer-main{
    padding:10px 20px 20px 20px;
    border-top: 1px solid #e3e3e3;
    margin-top: 20px;
  }

</style>
